document.addEventListener('DOMContentLoaded', function() {
    // API基础URL
    const API_BASE_URL = 'http://localhost:8088/api/bookmarks';
    const TAGS_API_URL = 'http://localhost:8088/api/tags';

    // DOM元素
    const bookmarksContainer = document.getElementById('bookmarksContainer');
    const addBookmarkBtn = document.getElementById('addBookmarkBtn');
    const bookmarkModal = document.getElementById('bookmarkModal');
    const modalTitle = document.getElementById('modalTitle');
    const bookmarkForm = document.getElementById('bookmarkForm');
    const bookmarkIdInput = document.getElementById('bookmarkId');
    const bookmarkTitleInput = document.getElementById('bookmarkTitle');
    const bookmarkUrlInput = document.getElementById('bookmarkUrl');
    const bookmarkImageInput = document.getElementById('bookmarkImage');
    const cancelBtn = document.getElementById('cancelBtn');
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    const tagFilter = document.getElementById('tagFilter');
    const tagSelector = document.getElementById('tagSelector');

    // 当前编辑的书签ID
    let editingId = null;
    let allTags = [];

    // 初始化页面
    init();

    function init() {
        fetchTags().then(fetchBookmarks);

        // 事件监听
        addBookmarkBtn.addEventListener('click', showAddModal);
        cancelBtn.addEventListener('click', hideModal);
        bookmarkForm.addEventListener('submit', handleFormSubmit);
        searchBtn.addEventListener('click', handleSearch);
        searchInput.addEventListener('keyup', function(e) {
            if (e.key === 'Enter') handleSearch();
        });
        tagFilter.addEventListener('change', handleTagFilter);
    }

    // 获取所有标签
    async function fetchTags() {
        try {
            const response = await fetch(TAGS_API_URL);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            allTags = await response.json();
            renderTagFilter();
            return allTags;
        } catch (error) {
            console.error('Error fetching tags:', error);
            return [];
        }
    }

    // 渲染标签筛选器
    function renderTagFilter() {
        tagFilter.innerHTML = '<option value="">所有标签</option>';
        allTags.forEach(tag => {
            const option = document.createElement('option');
            option.value = tag.id;
            option.textContent = tag.name;
            tagFilter.appendChild(option);
        });
    }

    // 获取所有书签
    async function fetchBookmarks() {
        showLoading();

        try {
            const response = await fetch(API_BASE_URL);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const bookmarks = await response.json();
            renderBookmarks(bookmarks);
        } catch (error) {
            showError('加载书签失败，请刷新重试');
            console.error('Error fetching bookmarks:', error);
        }
    }

    // 渲染书签列表
    function renderBookmarks(bookmarks) {
        bookmarksContainer.innerHTML = '';

        if (bookmarks.length === 0) {
            bookmarksContainer.innerHTML = `
                <div class="no-results" style="grid-column: 1 / -1; text-align: center; padding: 40px;">
                    <p>暂无收藏的网址</p>
                    <button id="addFirstBookmark" class="add-btn" style="margin-top: 20px;">添加第一个书签</button>
                </div>
            `;

            document.getElementById('addFirstBookmark')?.addEventListener('click', showAddModal);
            return;
        }

        bookmarks.forEach(bookmark => {
            const card = createBookmarkCard(bookmark);
            bookmarksContainer.appendChild(card);
        });
    }

    // 创建书签卡片
    function createBookmarkCard(bookmark) {
        const card = document.createElement('div');
        card.className = 'bookmark-card';

        // 构建标签HTML
        let tagsHtml = '';
        if (bookmark.tags && bookmark.tags.length > 0) {
            tagsHtml = `<div class="bookmark-tags">${bookmark.tags.map(tag =>
                `<span class="bookmark-tag" style="background-color: ${tag.color}">${tag.name}</span>`
            ).join('')}</div>`;
        }

        card.innerHTML = `
            <div class="bookmark-image">
                ${bookmark.imageUrl
            ? `<img src="${bookmark.imageUrl}" alt="${bookmark.title}" 
                         onerror="this.parentElement.innerHTML='<div class=\\'no-image\\'><img src=\\'/images/no-image.png\\' alt=\\'无预览图\\'></div>'">`
            : `<div class="no-image"><img src="/images/no-image.png" alt="无预览图"></div>`}
            </div>
            <div class="bookmark-info">
                <h3 class="bookmark-title" title="${bookmark.title}">${bookmark.title}</h3>
                ${tagsHtml}
                <p class="bookmark-url" title="${bookmark.url}">${bookmark.url}</p>
                <div class="bookmark-actions">
                    <a href="${bookmark.url}" target="_blank" class="visit-btn">访问</a>
                    <div>
                        <button class="edit-btn" data-id="${bookmark.id}">编辑</button>
                        <button class="delete-btn" data-id="${bookmark.id}">删除</button>
                    </div>
                </div>
            </div>
        `;

        // 添加事件监听
        card.querySelector('.edit-btn').addEventListener('click', () => editBookmark(bookmark.id));
        card.querySelector('.delete-btn').addEventListener('click', () => deleteBookmark(bookmark.id));

        return card;
    }

    // 显示添加模态框
    function showAddModal() {
        editingId = null;
        modalTitle.textContent = '添加新网址';
        bookmarkForm.reset();
        bookmarkIdInput.value = '';
        renderTagSelector([]);
        showModal();
    }

    // 渲染标签选择器
    function renderTagSelector(selectedTagIds = []) {
        tagSelector.innerHTML = '';

        allTags.forEach(tag => {
            const isSelected = selectedTagIds.includes(tag.id);
            const tagOption = document.createElement('label');
            tagOption.className = 'tag-option';
            tagOption.style.backgroundColor = isSelected ? tag.color + '30' : '#f5f5f5';
            tagOption.style.border = `1px solid ${isSelected ? tag.color : '#ddd'}`;

            tagOption.innerHTML = `
                <input type="checkbox" value="${tag.id}" ${isSelected ? 'checked' : ''}>
                <span style="color: ${tag.color}">${tag.name}</span>
            `;

            tagOption.querySelector('input').addEventListener('change', function() {
                tagOption.style.backgroundColor = this.checked ? tag.color + '30' : '#f5f5f5';
                tagOption.style.border = `1px solid ${this.checked ? tag.color : '#ddd'}`;
            });

            tagSelector.appendChild(tagOption);
        });
    }

    // 显示编辑模态框
    async function editBookmark(id) {
        try {
            const response = await fetch(`${API_BASE_URL}/${id}`);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const bookmark = await response.json();

            editingId = id;
            modalTitle.textContent = '编辑网址';
            bookmarkIdInput.value = id;
            bookmarkTitleInput.value = bookmark.title;
            bookmarkUrlInput.value = bookmark.url;
            bookmarkImageInput.value = bookmark.imageUrl || '';

            // 渲染标签选择器并选中已有标签
            const selectedTagIds = bookmark.tags ? bookmark.tags.map(tag => tag.id) : [];
            renderTagSelector(selectedTagIds);

            showModal();
        } catch (error) {
            showError('获取书签信息失败');
            console.error('Error fetching bookmark:', error);
        }
    }

    // 删除书签
    async function deleteBookmark(id) {
        if (!confirm('确定要删除这个书签吗？')) return;

        try {
            const response = await fetch(`${API_BASE_URL}/${id}`, {
                method: 'DELETE'
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            fetchBookmarks();
        } catch (error) {
            showError('删除书签失败');
            console.error('Error deleting bookmark:', error);
        }
    }

    // 处理表单提交
    async function handleFormSubmit(e) {
        e.preventDefault();

        const title = bookmarkTitleInput.value.trim();
        const url = bookmarkUrlInput.value.trim();
        const imageUrl = bookmarkImageInput.value.trim();

        // 验证输入
        if (!title || !url) {
            alert('标题和网址是必填项');
            return;
        }

        try {
            new URL(url); // 验证URL格式
            if (imageUrl) new URL(imageUrl);
        } catch {
            alert('请输入有效的网址');
            return;
        }

        // 获取选中的标签ID
        const selectedTags = Array.from(tagSelector.querySelectorAll('input:checked')).map(el => el.value);

        const bookmarkData = {
            title,
            url,
            imageUrl: imageUrl || null,
            tagIds: selectedTags
        };

        try {
            let response;

            if (editingId) {
                // 更新书签
                response = await fetch(`${API_BASE_URL}/${editingId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(bookmarkData)
                });
            } else {
                // 创建书签
                response = await fetch(API_BASE_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(bookmarkData)
                });
            }

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            hideModal();
            fetchBookmarks();
        } catch (error) {
            showError(editingId ? '更新书签失败' : '添加书签失败');
            console.error('Error saving bookmark:', error);
        }
    }

    // 处理标签筛选
    async function handleTagFilter() {
        const tagId = tagFilter.value;

        if (!tagId) {
            fetchBookmarks();
            return;
        }

        showLoading();

        try {
            const response = await fetch(`${API_BASE_URL}?tagId=${tagId}`);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const results = await response.json();
            renderBookmarks(results);
        } catch (error) {
            showError('筛选失败，请重试');
            console.error('Error filtering bookmarks:', error);
        }
    }

    // 处理搜索
    async function handleSearch() {
        const query = searchInput.value.trim();
        const tagId = tagFilter.value;

        let url = `${API_BASE_URL}/search?query=${encodeURIComponent(query)}`;
        if (tagId) url += `&tagId=${tagId}`;

        if (!query && !tagId) {
            fetchBookmarks();
            return;
        }

        showLoading();

        try {
            const response = await fetch(url);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const results = await response.json();
            renderBookmarks(results);
        } catch (error) {
            showError('搜索失败，请重试');
            console.error('Error searching bookmarks:', error);
        }
    }

    // 显示加载状态
    function showLoading() {
        bookmarksContainer.innerHTML = `
            <div class="loading" style="grid-column: 1 / -1;">
                <p>加载中...</p>
            </div>
        `;
    }

    // 显示错误信息
    function showError(message) {
        bookmarksContainer.innerHTML = `
            <div class="error-message" style="grid-column: 1 / -1;">
                <p>${message}</p>
                <button class="add-btn" onclick="location.reload()" style="margin-top: 15px;">刷新页面</button>
            </div>
        `;
    }

    // 显示模态框
    function showModal() {
        bookmarkModal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
    }

    // 隐藏模态框
    function hideModal() {
        bookmarkModal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }
});